﻿using System;
using System.Collections.Generic;
using YKXiangQi.Common;
using YKXiangQi.Enums;
using YKXiangQi.Utilities;

namespace YKXiangQi.Models
{
    public class MoveList
    {
        public MoveList()
        {
            Moves = new List<Move>();
        }

        public string StartFen { get; set; }

        public List<Move> Moves { get; set; }

        public override string ToString()
        {
            string result = string.Empty;
            var moves = GenerateMoveDetailsList();
            foreach (var moveDetails in moves)
            {
                result += moveDetails.Notation + " ";
            }

            return result;
        }

        public List<MoveDetails> GenerateMoveDetailsList()
        {
            var result = new List<MoveDetails>();
            var fenInfo = FenReader.Read(StartFen);
            var pieces = fenInfo.Pieces;
            var side = fenInfo.ActiveColor;
            var moveNumber = 0;

            foreach (var move in Moves)
            {
                moveNumber++;
                var piece = pieces[move.From.Y, move.From.X];
                var notation = Helper.GetMoveLocalNotation(pieces, move);
                pieces[move.From.Y, move.From.X] = null;
                pieces[move.To.Y, move.To.X] = piece;
                var fen = Helper.GetFen(pieces, side);

                side = side == Sides.Red ? Sides.Black : Sides.Red;
                result.Add(new MoveDetails()
                               {
                                   Fen = fen,
                                   MoveNumber = moveNumber,
                                   Notation = notation
                               });
            }

            return result;
        }
    }
}
